/*
Copyright (C) 2007 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// This file is not yet used, though will be very useful in the future if
// deciding to use Google API to get cache instead of going to the actual
// Wikipedia page. (i.e. faster results)

// Do a Google Search Query using the public Google Search API
function GoogleQuery(APIKey, onDataCallback) {
  var APIKey_ = APIKey;
  var onDataCallback_ = onDataCallback;   // (data)
  var googleRequest_ = null;
  var stop_ = false;

  // Do the Google Search API request
  function query(searchTerms, opt_numResults, opt_startPosition) {
    assert(googleRequest_ == null, "A Google Web query is already active");

    var numResults = (opt_numResults == null) ? 10 : opt_numResults;
    var startPosition = (opt_startPosition == null) ? 1 : opt_startPosition;

    googleRequest_ = new XMLHttpRequest();  
    googleRequest_.open("POST", "http://api.google.com/search/beta2", true);
    googleRequest_.onreadystatechange = onData;
    googleRequest_.setRequestHeader("Man", 
      "POST http://api.google.com/search/beta2 HTTP/1.1");
    googleRequest_.setRequestHeader("MessageType", "CALL");
    googleRequest_.setRequestHeader("Content-Type", "text/xml");
    stop_ = false;
  
    // Make the search terms safe
    var safeSearchTerms = searchTerms.replace(/[<]/g, "&lt;");
    safeSearchTerms = safeSearchTerms.replace(/[>]/g, "&gt;");

    try {
      googleRequest_.send("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n\n" + 
        "<SOAP-ENV:Envelope " +
        " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
        " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\"" +
        " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">" +
        "<SOAP-ENV:Body><ns1:doGoogleSearch" +
        " xmlns:ns1=\"urn:GoogleSearch\"" +
        " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" +
          "<key xsi:type=\"xsd:string\">" + APIKey_ + "</key>" + 
          "<q xsi:type=\"xsd:string\">" + safeSearchTerms + "</q>" + 
          "<start xsi:type=\"xsd:int\">" + parseInt(startPosition) + "</start>" + 
          "<maxResults xsi:type=\"xsd:int\">" + parseInt(numResults) + "</maxResults>" + 
          "<filter xsi:type=\"xsd:boolean\">false</filter>" + 
          "<restrict xsi:type=\"xsd:string\"></restrict>" + 
          "<safeSearch xsi:type=\"xsd:boolean\">false</safeSearch>" + 
          "<lr xsi:type=\"xsd:string\"></lr>" + 
          "<ie xsi:type=\"xsd:string\">latin1</ie>" + 
          "<oe xsi:type=\"xsd:string\">latin1</oe>" +
        "</ns1:doGoogleSearch>" +
        "</SOAP-ENV:Body></SOAP-ENV:Envelope>");
    } catch(e) {
      googleRequest_ = null;
      onDataCallback(null);
    }
  }

  // Stop the current transfer. No data callbacks will be made for this request.
  function stop() {
    assert(googleRequest_ != null, "A request is not active");

    stop_ = true;
    googleRequest_.abort();
    googleRequest_ = null;
  }
  
  // Called when data or status changes with the XMLHttpRequest
  function onData() {
    // If the download has been stopped, do not continue
    if (stop_)
      return;

    // If the data is not ready (still downloading), do not continue
    assert(googleRequest_ != null, "A request is not active");
    if (googleRequest_.readyState != 4)
      return;

    // If there was an http error, do not continue
    if (googleRequest_.status != 200) {
      onDataCallback(null);
      return;
    }

    onDataCallback(googleRequest_.responseText);
    googleRequest_ = null;
  }

  this.query = query;
  this.stop = stop;
}
